package cn.kgc.easybuy.service.impl;

import cn.kgc.easybuy.dao.OrderMapper;
import cn.kgc.easybuy.dao.ProductESRepository;
import cn.kgc.easybuy.pojo.Order;
import cn.kgc.easybuy.pojo.OrderDetial;
import cn.kgc.easybuy.pojo.Product;
import cn.kgc.easybuy.service.OrderDetialService;
import cn.kgc.easybuy.service.OrderService;
import cn.kgc.easybuy.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.util.ToStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetialService orderDetialService;

    @Autowired
    private ProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductESRepository productESRepository;

    private static final String ORDER_EXPIRE_KEY_PREFIX = "order:";

    @Override
    public boolean delOrder(Integer id) {
        int flag = orderMapper.delOrder(id);
        if (flag==1){
            return true;
        }else {
            throw new RuntimeException("删除订单"+id+"失败");
        }
    }

    @Override
    public boolean updateOrder(Order order) {
        int flag = orderMapper.updateOrder(order);
        if (flag==1){
            return true;
        }else {
            throw new RuntimeException("修改订单"+order.getId()+"失败");
        }
    }

    @Override
    public boolean addOrder(Order order) {
        // 校验库存
        for (OrderDetial orderDetial : order.getOrderDetialList()) {
            Product product1 = productService.selectProductById(orderDetial.getProductId());
            if (orderDetial.getQuantity() > product1.getStock()){
                throw new RuntimeException("商品"+product1.getName()+"库存不足！订单创建失败");
            }
        }

        order.setCreateTime(new Date());
        order.setSerialNumber(UUID.randomUUID().toString().replace("-", ""));
        order.setState(0);
        order.setIsDelete(0);

        int flag = orderMapper.addOrder(order);
        int orderId = order.getId();

        boolean orderFlag = false;
        for (OrderDetial orderDetial : order.getOrderDetialList()) {
            orderDetial.setOrderId(orderId);
            // 将订单详情写入数据库
            orderFlag = orderDetialService.addOrderDetial(orderDetial);
            // 库存数据更新
            int productId = orderDetial.getProductId();
            int quantity = orderDetial.getQuantity();
            Product product = productService.selectProductById(productId);
            product.setId(productId+"");
            product.setStock(product.getStock()-quantity);
            product.setOrderStock(product.getOrderStock()+quantity);
            orderFlag = productService.sellProduct(product);
            productESRepository.save(product);
            if (!orderFlag){
                throw new RuntimeException("添加订单"+order.getId()+"失败");
            }

        }

        // 更新ES
        productService.saveAllProductToEs();
        //将添加订单添加至redis中
        redisTemplate.opsForValue().set(ORDER_EXPIRE_KEY_PREFIX+order.getSerialNumber(),orderId,15, TimeUnit.MINUTES);

        if (flag == 1){
            return true;
        }else {
            throw new RuntimeException("添加订单"+order.getId()+"失败");
        }
    }

    @Override
    public Order selectOrderById(Integer id) {
        Order order = orderMapper.selectOrderById(id);
        if (order!=null){
            List<OrderDetial> orderDetialList = orderDetialService.selectOrderDetialByOrderId(id);
            order.setOrderDetialList(orderDetialList);
            return order;
        }else {
            throw new RuntimeException("查询订单"+id+"失败");
        }
    }

    @Override
    public Order selectOrderBySerialNumber(String serialNumber) {
        return orderMapper.selectOrderBySerialNumber(serialNumber);
    }

    @Override
    public PageInfo<Order> selectOrderByPage(Map<String, Object> params) {
        PageHelper.startPage(params);
        List<Order> orderlist = orderMapper.selectOrderByPage(params);
        if (orderlist!=null && orderlist.size()>0){
            for (Order order : orderlist){
                int id = order.getId();
                List<OrderDetial> orderDetialList = orderDetialService.selectOrderDetialByOrderId(id);
                order.setOrderDetialList(orderDetialList);
            }
        }
        PageInfo<Order> pageInfo = new PageInfo<>(orderlist);
        return pageInfo;
    }

    @Override
    public boolean sellOrder(Order order) {
        List<OrderDetial> orderDetialList = order.getOrderDetialList();
        boolean flag = true;
        for (OrderDetial orderDetial : orderDetialList){
            int productId = orderDetial.getProductId();
            int quantity = orderDetial.getQuantity();
            Product product = productService.selectProductById(productId);
            product.setId(productId+"");
            product.setOrderStock(product.getOrderStock()-quantity);
            product.setSales(product.getSales()+quantity);
            flag = productService.sellProduct(product);
            productESRepository.save(product);
            if (!flag){
                throw new RuntimeException("订单"+order.getId()+"销售失败");
            }
        }
        // 更新ES
        productService.saveAllProductToEs();
        return  true;
    }

    @Override
    public boolean refundOrder(Order order) {
        List<OrderDetial> orderDetialList = order.getOrderDetialList();
        boolean flag = true;
        for (OrderDetial orderDetial : orderDetialList){
            int productId = orderDetial.getProductId();
            int quantity = orderDetial.getQuantity();
            Product product = productService.selectProductById(productId);
            product.setId(productId+"");
            product.setStock(product.getStock()+quantity);
            product.setSales(product.getSales()-quantity);
            flag = productService.refundProduct( product);
            productESRepository.save(product);
            if (!flag){
                throw new RuntimeException("订单"+order.getId()+"退款失败");
            }
        }
        // 更新ES
        productService.saveAllProductToEs();
        return  true;
    }

    @Override
    public boolean cancelOrder(Integer id) {
        Order order = selectOrderById(id);
        List<OrderDetial> orderDetialList = order.getOrderDetialList();
        boolean flag = true;
        order.setState(2);
        flag = orderMapper.updateOrder(order) == 1;
        if (!flag){
            throw new RuntimeException("订单"+order.getId()+"取消失败");
        }
        for (OrderDetial orderDetial : orderDetialList){
            int productId = orderDetial.getProductId();
            int quantity = orderDetial.getQuantity();
            Product product = productService.selectProductById(productId);
            product.setId(productId+"");
            product.setStock(product.getStock()+quantity);
            product.setOrderStock(product.getOrderStock()-quantity);
            flag = productService.refundProduct( product);
            if (!flag){
                throw new RuntimeException("订单"+order.getId()+"取消失败");
            }

        }
        // 更新ES
        productService.saveAllProductToEs();
        // 删除redis中当前存储订单计时
        redisTemplate.delete(ORDER_EXPIRE_KEY_PREFIX+order.getSerialNumber());
        return  true;
    }
}
